package com.xmtlxx.web.controller.tms.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.xmtlxx.web.controller.tms.service.IOrderService;
import com.xmtlxx.web.controller.tms.service.IWaybillDtlService;
import com.xmtlxx.web.controller.tms.service.IWaybillLogService;
import com.xmtlxx.web.controller.tms.service.IWaybillService;
import com.xmtlxx.common.annotation.Log;
import com.xmtlxx.common.annotation.RepeatSubmit;
import com.xmtlxx.common.core.controller.BaseController;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.R;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.core.validate.AddGroup;
import com.xmtlxx.common.core.validate.EditGroup;
import com.xmtlxx.common.core.validate.QueryGroup;
import com.xmtlxx.common.enums.BusinessType;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.utils.poi.ExcelUtil;
import com.xmtlxx.tms.domain.Waybill;
import com.xmtlxx.tms.domain.bo.OrderBo;
import com.xmtlxx.tms.domain.bo.WaybillBo;
import com.xmtlxx.tms.domain.bo.WaybillDtlBo;
import com.xmtlxx.tms.domain.bo.WaybillLogBo;
import com.xmtlxx.tms.domain.vo.OrderVo;
import com.xmtlxx.tms.domain.vo.WaybillVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 运单Controller
 *
 * @author xmtlxx
 * @date 2022-08-15
 */
@Validated
@Api(value = "运单控制器", tags = {"运单管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/tms/waybill")
public class WaybillController extends BaseController {

    private final IWaybillService iWaybillService;

    private final IWaybillDtlService iWaybillDtlService;

    private final IWaybillLogService iWaybillLogService;

    private final IOrderService iOrderService;

    /**
     * 返回一个初始化的对象到前端，方便进行动态渲染
     */
    @ApiOperation("用于返回一个初始化对象")
    @PostMapping("/initBean")
    R<WaybillVo> initBean(){
        WaybillVo vo = new WaybillVo();
        //可以对数据进行初始化
        return R.ok(vo);
    }

    /**
     * 查询运单列表
     */
    @ApiOperation("查询运单列表")
//    @SaCheckPermission("tms:waybill:list")
    @GetMapping("/list")
    public TableDataInfo<WaybillVo> list(@Validated(QueryGroup.class) WaybillBo bo, PageQuery pageQuery) {
        if(LoginHelper.getLoginUser().getRolePermission().contains("smscys")){
            bo.setCarrierDeptId(LoginHelper.getDeptId());
        }else if(LoginHelper.getLoginUser().getRolePermission().contains("qujianyuan") || LoginHelper.getLoginUser().getRolePermission().contains("paijianyuan")){
            bo.setPickupId(LoginHelper.getUserId());
        }else{
            bo.setStoreDeptId(LoginHelper.getDeptId());
        }
        return iWaybillService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询订单是否绑定视频
     */
    @ApiOperation("查询订单是否绑定视频")
    @GetMapping("/getTaskVideoStatus/{id}")
    public R<String> getTaskVideoStatus(@ApiParam("主键")
                                        @NotNull(message = "主键不能为空")
                                        @PathVariable("id") String id){
        String num = iWaybillService.getTaskVideoStatus(id);
        return R.ok("成功",num);
    }

    /**
     * 导出运单列表
     */
    @ApiOperation("导出运单列表")
    @SaCheckPermission("tms:waybill:export")
    @Log(title = "运单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@Validated WaybillBo bo, HttpServletResponse response) {
        List<WaybillVo> list = iWaybillService.queryList(bo);
        ExcelUtil.exportExcel(list, "运单", WaybillVo.class, response);
    }

    /**
     * 获取运单详细信息
     */
    @ApiOperation("获取运单详细信息")
//    @SaCheckPermission("tms:waybill:query")
    @GetMapping("/{id}")
    public R<WaybillVo> getInfo(@ApiParam("主键")
                                     @NotNull(message = "主键不能为空")
                                     @PathVariable("id") String id) {
        WaybillVo vo = iWaybillService.queryById(id);
        WaybillDtlBo bo = new WaybillDtlBo();
        bo.setWaybillId(vo.getId());
        vo.setItems(iWaybillDtlService.queryList(bo));

        WaybillLogBo waybillLogBo = new WaybillLogBo();
        waybillLogBo.setTrackId(vo.getId());
        vo.setLogItems(iWaybillLogService.queryList(waybillLogBo));

        if(LoginHelper.getLoginUser().getRolePermission().contains("Admin")){
            vo.setIsShow(true);
        } else if(LoginHelper.getLoginUser().getRolePermission().contains("smscg")){
            vo.setIsShow(true);
        } else {
            vo.setIsShow(false);
        }

        OrderVo orderVo = iOrderService.queryById(vo.getOrderId());
        if(orderVo != null){
            vo.setCarStatus(orderVo.getCarStatus());
            if(orderVo.getStatus().equals("2")){
                vo.setIsShow(true);
            }else {
                vo.setIsShow(false);
            }
        }else {
            vo.setIsShow(false);
        }

        return R.ok(vo);
    }

    /**
     * 新增运单
     */
    @ApiOperation("新增运单")
    @SaCheckPermission("tms:waybill:add")
    @Log(title = "运单", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    @Transactional(rollbackFor = Exception.class)
    public R<WaybillVo> add(@Validated(AddGroup.class) @RequestBody WaybillVo vo) {
        WaybillBo bo = new WaybillBo();
        BeanUtil.copyProperties(vo,bo);
        return R.ok(iWaybillService.insertByBo(bo));
    }

    /**
     * 修改运单
     */
    @ApiOperation("修改运单")
    @SaCheckPermission("tms:waybill:edit")
    @Log(title = "运单", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    @Transactional(rollbackFor = Exception.class)
    public R<WaybillVo> edit(@Validated(EditGroup.class) @RequestBody WaybillVo vo) {
        WaybillBo bo = new WaybillBo();
        BeanUtil.copyProperties(vo,bo);
        return R.ok(iWaybillService.updateByBo(bo));
    }

    /**
     * 删除运单
     */
    @ApiOperation("删除运单")
    @SaCheckPermission("tms:waybill:remove")
    @Log(title = "运单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public R<Void> remove(@ApiParam("主键串")
                          @NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(iWaybillService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

    /**
     * 接单
     */
    @ApiOperation("接单")
    @SaCheckPermission("tms:waybill:receive")
    @Log(title = "运单", businessType = BusinessType.UPDATE)
    @PostMapping("receive/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public R<Void> receive(@ApiParam("主键串")
                          @NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        List<Waybill> waybills = new ArrayList<>();
        for (String id:ids){
            WaybillVo waybillVo = iWaybillService.queryById(id);
            Waybill bo = new Waybill();
            BeanUtil.copyProperties(waybillVo,bo);

            bo.setStatus("1");
            bo.setTakeBillTime(new Date());
            waybills.add(bo);
        }
        return toAjax(iWaybillService.updateWithValidByIds(waybills, true) ? 1 : 0);
    }


    /**
     * 装车
     */
    @ApiOperation("装车")
    @SaCheckPermission("tms:waybill:entruck")
    @Log(title = "运单", businessType = BusinessType.UPDATE)
    @PostMapping("entruck/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public R<Void>  entruck(@ApiParam("主键串")
                          @NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        List<Waybill> waybills = new ArrayList<>();
        for (String id:ids){
            WaybillVo waybillVo = iWaybillService.queryById(id);
            Waybill bo = new Waybill();
            BeanUtil.copyProperties(waybillVo,bo);

            bo.setStatus("2");
            bo.setTakeTime(new Date());//装车时间
            waybills.add(bo);
        }
        return toAjax(iWaybillService.updateWithValidByIds(waybills, true) ? 1 : 0);
    }


    /**
     * 发车
     */
    @ApiOperation("发车")
    @Log(title = "运单", businessType = BusinessType.UPDATE)
    @PostMapping("depart/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public R<Void> depart(@ApiParam("主键串")
                          @NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        List<Waybill> waybills = new ArrayList<>();
        for (String id:ids){
            WaybillVo waybillVo = iWaybillService.queryById(id);
            Waybill bo = new Waybill();
            BeanUtil.copyProperties(waybillVo,bo);

            bo.setStatus("3");
            bo.setSendTime(new Date());

            OrderVo orderVo = iOrderService.queryById(waybillVo.getOrderId());
            //配送时间
            orderVo.setDeliveryTime(new Date());
            OrderBo orderBo = new OrderBo();
            BeanUtil.copyProperties(orderVo,orderBo);
            iOrderService.updateByBo(orderBo);

            waybills.add(bo);
        }
        return toAjax(iWaybillService.updateWithValidByIds(waybills, true) ? 1 : 0);
    }

    @GetMapping("/getSignByWaybill/{boxNo}")
    public R<String> getSignByWaybill(@PathVariable String boxNo){
        return R.ok(iWaybillService.getSignByWaybill(boxNo,"5"));
    }

}
